class CodeHighlighter {
    constructor() {
      this.editor = document.querySelector('.editor-content');
      this.theme = 'default';
      this.language = 'javascript'; // 默认支持JS
      this.debounceTimer = null;
  
      // 初始化样式
      this.loadTheme();
      
      // 监听编辑器变化
      this.editor.addEventListener('input', () => this.debounceHighlight());
      
      // 初始化高亮
      this.highlight();
    }
  
    loadTheme() {
      const themeLink = document.createElement('link');
      themeLink.rel = 'stylesheet';
      themeLink.href = `extensions/code-highlighter/themes/${this.theme}.css`;
      document.head.appendChild(themeLink);
    }
  
    debounceHighlight() {
      clearTimeout(this.debounceTimer);
      this.debounceTimer = setTimeout(() => this.highlight(), 300);
    }
  
    highlight() {
      const code = this.editor.textContent;
      const tokens = this.tokenize(code);
      this.editor.innerHTML = this.renderTokens(tokens);
    }
  
    tokenize(code) {
      const tokens = [];
      let pos = 0;
      
      // 基础语法规则（可扩展）
      const rules = [
        { regex: /("|')(\\?.)*?\1/g, type: 'string' },
        { regex: /\/\/.*|\/\*[\s\S]*?\*\//g, type: 'comment' },
        { regex: /\b(function|return|if|else|for|while)\b/g, type: 'keyword' },
        { regex: /\b\d+\b/g, type: 'number' },
        { regex: /[a-zA-Z_]\w*/g, type: 'identifier' }
      ];
  
      while(pos < code.length) {
        let matched = false;
        for (const rule of rules) {
          rule.regex.lastIndex = pos;
          const match = rule.regex.exec(code);
          if (match && match.index === pos) {
            tokens.push({
              type: rule.type,
              value: match[0]
            });
            pos = match.index + match[0].length;
            matched = true;
            break;
          }
        }
        if (!matched) {
          tokens.push({
            type: 'text',
            value: code[pos++]
          });
        }
      }
      return tokens;
    }
  
    renderTokens(tokens) {
      return tokens.map(token => {
        if (token.type === 'text') return token.value;
        return `<span class="token ${token.type}">${this.escapeHtml(token.value)}</span>`;
      }).join('');
    }
  
    escapeHtml(unsafe) {
      return unsafe.replace(/[&<>"']/g, m => ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
      }[m]));
    }
  }
  
  // 初始化高亮器
  new CodeHighlighter();